<template>
  <div class="screenshots" :id="'demo' + order">
    <div class="img" :class="activeClass" @click="addMark($event,true)">
      <pdf
        v-if="fileType === 'pdf'"
        :src="url"
        @page-loaded="handLoaded"
        :page="pageIndex"/>
      <img v-else :src="url" alt="">
      <template  v-for="(item,index) in markS">
        <i
          v-if="!item.itemDelete"
          @dblclick="handShowItem(index)"
          @contextmenu.prevent="handMore($event,index)"
          @mouseenter="handMouseIn(index)"
          @mouseleave="handMouseOut(index)"
          class="iconfont cyy-xingzhuang1 marks"
          :class="item.className"
          :key="index" slot="suffixIcon"
          :style="'left:' + item.x + ';top:' + item.y + ';'"
          :ref="'start' + item.id"
          :id="'start' + item.id"
        ></i>
      </template>
    </div>
    <ul  class="scrollCont">
      <template v-for="(it,index) in markS">
        <li v-if="it.show && !it.itemDelete"
            :key="it.id"
            :ref="'end' + it.id"
            :id="'end' + it.id"
            @mouseenter="handMouseIn(index)"
            @mouseleave="handMouseOut(index)"
            :class="preview === 'true' ? 'pd_bottom': ''"
        >
          <p class="notation_titile clear">
              <span class="fl">批注</span>
              <span class="notation_time fr">{{ markS[index].time }}</span>
          </p>
          <div class="clear">
            <p class="notation_name fl">{{ markS[index].name }}</p>
          </div>
          <i class="iconfont cyy-close" slot="suffixIcon" @click="handDelete(index)"></i>
          <a-textarea @change="handInputChange" :disabled="preview === 'true'" v-model="markS[index].content" placeholder="请输入批注内容" :rows="4" />
          <div class="save_box" v-if="preview === 'false'">
            <promptInfo @clickOn="handSave" class="save" :title="'保存'" :iconfont="'cyy-baocun'"></promptInfo>
          </div>
        </li>
      </template>
    </ul>
    <moreMenu
      ref="contextmenu"
      :menuList="menuList"
      @click="handMenuItemClick"
    ></moreMenu>
  </div>
</template>

<script>
import LeaderLine from 'leader-line-vue'
import PlainDraggable from 'plain-draggable'
import pdf from 'vue-pdf'
import moreMenu from "./moreMenu";
import {formatTime} from "@/tools/util";
export default {
  name: "documentDetails",
  components:{
    pdf,
    moreMenu
  },
  props: {
    fileType:{
      default: 'pdf',
    }, // 文件类型
    url:{
      default: '',
    }, // url路径
    order: {
      type: Number,
      default() {
        return 0
      }
    }, // 当序号用
    pageIndex: {
      type: Number,
      default() {
        return 0
      }
    }, // 页码
    markS: {
      type: Array,
      default() {
        return []
      }
    }, // 批注标志
    allowMark:{
      type: Boolean,
      default() {
        return false
      }
    }, // 是否可以添加批注
    createItem:{
      type:Array,
      default(){
        return []
      }
    }, // 具体信息
    preview:{
      type: String,
      default() {
        return 'false'
      }
    } // 预览
  },
  created() {

  },
  data() {
    return {
      pdfUrl: '',
      totalPage: [],
      loadedRatio: 0,
      colorS: ['#3598F9','#FFAF00','#AF00FF','#ff973b'], // 批注的颜色
      activeClass: '', // 当前激活的批注鼠标样式
      iconClass: ['cursor_blue','cursor_yellow','cursor_purple','cursor_orange'], // 批注的鼠标样式
      menuList: [
        {
          menuName: "删除",
          iconName: "cyy-shanchu",
          event: 'delete'
        },
      ], // 菜单列表
      selectIndex: -1,
    }
  },
  methods: {
    // 保存按钮
    handSave(){
      this.$emit('confirm')
    },
    // 显示备注
    async handShowItem(key){
      if(!this.markS[key].show) {
        this.markS[key].show = true
        this.activeClass = 'cursor_' + this.markS[key].className
        await this.$nextTick(()=>{
          this.initNotation(key,false)
          this.fixPosition()
        })
        this.activeClass = ''
      }
    },
    // 右键菜单
    handMore(event,key){
      if (this.preview === 'false') {
        let clientX = event.pageX
        let clientY = event.pageY
        this.$refs.contextmenu.show({
          top: clientY,
          left: clientX,
        })
        this.selectIndex = key
      }
    },
    // 菜单
    handMenuItemClick() {
      this.$emit('change')
      if (this.markS[this.selectIndex].Line){
        this.markS[this.selectIndex].Line.remove()
      }
      this.markS[this.selectIndex].draggable.remove()
      this.markS[this.selectIndex].draggable = null
      this.markS[this.selectIndex].Line = null
      this.markS[this.selectIndex].itemDelete = true
      this.selectIndex = -1
    },
    // 鼠标移入
    handMouseIn(operationIndex){
      if( this.markS[operationIndex].show && this.markS[operationIndex].Line){
        this.markS[operationIndex].Line.show()
      }
      this.fixPosition()
    },
    // 鼠标离开
    handMouseOut(operationIndex){
      if(this.markS[operationIndex].Line){
        this.markS[operationIndex].Line.hide()
      }
    },
    // 加载完成
    handLoaded(num){
      const that = this
      let timer1 = setTimeout(function(){
        clearTimeout(timer1);
        that.init()
        that.$emit('success',num)
      }, 300);
    },
    // 初始化有值
    init(){
      this.$nextTick( () =>{
        this.createItem.forEach((item,index)=>{
          this.activeClass = 'cursor_' + item.className
          let solidColor = this.colorS[this.iconClass.findIndex(item => {
            return item === this.activeClass
          })]
          this.addMark({
            layerX: parseInt(item.x),
            layerY: parseInt(item.y),
            solidColor
          },false)
          this.markS[index].content = item.content
          this.markS[index].time = item.time
          this.markS[index].name = item.name
        })
      })
    },
    // 关闭当前备注
    handDelete(index){
      // 隐藏实例化的线条
      this.markS[index].Line.remove()
      if (this.markS[index].draggable){
        this.markS[index].draggable.remove()
      }
      this.markS[index].Line = null
      this.markS[index].draggable = null
      let startEle = this.$refs['start' + this.markS[index].id]
      if (this.preview === 'false'){
        this.markS[index].draggable = new PlainDraggable(startEle[0])
      }
      // 删除批注
      this.markS[index].show = false
      this.fixPosition()
    },
    // 添加批注
    async addMark(e,ischange){
      if (this.activeClass != '') {
        if(ischange){
          this.$emit('change')
        }
        // 线条颜色下标循环
        let operationIndex = this.markS.length
        let newMark = {
          x: e.layerX + 'px', // x坐标
          y: e.layerY + 'px', // y坐标
          className:this.activeClass.slice(7), // 标志class
          content: '', // 批注内容
          id:this.generateMixed(5), // id用于唯一标识
          itemDelete: false, // 是否删除
          show: true, // 是否展示批注框
          time: formatTime( Date.parse(new Date()),'Y-M-D h:m:s'), // 批注的时间
          name: this.$store.getters.getUserInfo.nickname, // 批注人名称
        }
        // 标志的位置
        this.markS.push(newMark)
        await this.$nextTick(() => {
          this.initNotation(operationIndex,true,e.solidColor)
        });
        this.activeClass = '';
        this.$emit('cancelMark')
      }
    },
    // 生成 UUID
    generateMixed(n) {
      let chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
      let res = "";
      for(let i = 0; i < n ; i ++) {
        let id = Math.ceil(Math.random()*35);
        res += chars[id];
      }
      return res;
    },
    // 修复位置
    fixPosition(){
      this.markS.forEach(item =>{
        if(item.show && !item.itemDelete){
          this.$nextTick(()=>{
            item.Line.position()
          })
        }
      });
    },
    // 备注内容修改
    handInputChange(){
      this.$emit('change')
    },
    // 初始化一对批注
    initNotation(operationIndex,intiShow,solidColor) {
      // 得到链接的两个dom元素
      let startEle = this.$refs['start' + this.markS[operationIndex].id]
      let endEle = this.$refs['end' + this.markS[operationIndex].id]
      // 连接线实例化
      this.markS[operationIndex].Line = LeaderLine.setLine(endEle[0],startEle[0],{animOptions: {
          duration: 0
        },hide:intiShow})
      // 线条颜色
      this.markS[operationIndex].Line.color = solidColor || this.colorS[this.iconClass.findIndex(item => {
        return item === this.activeClass
      })];
      // 去除默认箭头标志
      this.markS[operationIndex].Line.startPlug = 'behind';
      this.markS[operationIndex].Line.endPlug ='behind';
      // 线的粗细
      this.markS[operationIndex].Line.size = 3;
      // 右侧的文字备注线只能从左侧链接
      this.markS[operationIndex].Line.startSocket = 'left';
      if (this.preview === 'false'){
        // 实例化批注标志的移动功能
        this.markS[operationIndex].draggable = new PlainDraggable(startEle[0])
        // 标志移动的时给连接线进行刷新
        this.markS[operationIndex].draggable.onMove = () => {
          if( this.markS[operationIndex].show){
            this.markS[operationIndex].Line.position()
            this.$emit('change')
          }
        };
        // 释放移动发送后台请求保持位置
        this.markS[operationIndex].draggable.onDragEnd = () =>{
          let move = this.markS[operationIndex].draggable.element.style.getPropertyValue("transform").slice(10,-1).split(',');
          // 移动后的位置
          let left = parseInt(this.markS[operationIndex].x) + parseInt(move[0]) + 'px'
          let top = parseInt(this.markS[operationIndex].y) + parseInt(move[1]) + 'px'
          this.markS[operationIndex].changeX = left
          this.markS[operationIndex].changeY = top
        }
      }
    }
  },
  watch:{
    // 当a的值发生改变时触发
    allowMark:function(val){
      if (val){
        this.activeClass = this.iconClass[this.markS.length % 4];
      } else {
        this.activeClass = ''
      }
    },
    createItem:function(val){
      this.createItem = val
      if (this.fileType != 'pdf') {
        this.init()
      }
    },
  }
}
</script>

<style scoped lang="scss">
.container{
  padding-left: 20%;
  padding-right: 20%;
  padding-top: 24px;
  width: 100%;
  position: relative;
  //display flex;
  //justify-content:space-between;
  .screenshots{
    display: flex;
    justify-content:space-between;
  }
  .ant-btn{
    width: 112px;
    height: 36px;
    background: #3598F9;
    border-radius: 2px;
    font-size: 16px;
    position: absolute;
    left: 24px;
    top: 24px;
    //margin-right 150px
  }
  .cursor_blue{
    cursor:url("../../assets/image/literature/icon_blue.svg"),auto;
  }
  .cursor_yellow{
    cursor:url("../../assets/image/literature/icon_yellow.svg"),auto;
  }
  .cursor_purple{
    cursor:url("../../assets/image/literature/icon_purple.svg"),auto;
  }
  .cursor_orange{
    cursor:url("../../assets/image/literature/icon_orange.svg"),auto;
  }
  .img {
    position: relative;
    width: 800px;

    > img {
      width: auto;
      max-width: 100%;
      display: block;
      margin: 0 auto;
    }

    > span {
      width: 100%;
    }

    .marks {
      position: absolute;
      font-size: 16px;
      cursor: pointer;
    }

    .blue {
      color: #3598F9 !important;
    }

    .purple {
      color: #AF00FF !important;
    }

    .orange {
      color: #ff973b !important;
    }

    .yellow {
      color: #FFAF00 !important;
    }
  }
  img{
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
  ul {
    //margin-left  16px
    min-width: 270px;

    li {
      width: 270px;
      position: relative;
      min-height: 160px;
      height: auto;
      background: #F7F7F7;
      border-radius: 8px;
      margin-bottom: 16px;
      box-sizing: border-box;
      padding: 0px 12px 5px 12px;

      .iconfont {
        position: absolute;
        cursor: pointer;
        right: 5px;
        z-index: 10;
        font-size: 26px;
        top: 5px;
        color: #DEDEDE;
      }

      textarea.ant-input {
        box-shadow: none;
        padding-bottom: 0;
        border: none;
        background: #fff;
        min-height: 150px;
        height: auto;
      }

      .save_box {
        text-align: center;

        .save {
          position: relative;
          left: 0;
          top: 0;
          padding-top: 5px;
          font-size: 18px;
          color: #3598F9;
        }
      }
    }
  }
}
.notation_titile{
  padding-top: 10px;
  padding-bottom: 5px;
  margin-bottom: 0;
  >span{
    font-size: 16px;
    font-weight: bold;
  }
}
.notation_time{
  padding-right: 27px;
  font-size: 16px;
}
.notation_name{
  font-size: 16px;
  padding-bottom: 10px;
  margin-bottom:0;
}
.pd_bottom{
padding-bottom: 12px!important;
}
</style>
